02. Control Structures
Control Structures Review
Iteration with Loops
To iterate in Python, there are several options. A for
loop can be used to iterate through a list or dictionary. Instead of the traditional for
loop where we initialize a value i
and increase / decrease it till it reaches an end value, Python's for
loops are for-each
in nature. This means that when you are iterating using a for loop
over a list, you actually iterate over the items of that list.
If you also need the index values from the list while iterating, another possibility is to use enumerate
, which is shown in an example below.
An additional way to iterate in Python is with a while
loop. Just as in other programming languages, the while
loop will repeat while some conditional statement is true. You will see more on conditional statements shortly, but first, here are examples of iteration with for
and while
loops.
# Examples of iteration with for loops.
my_list = [0, 1, 2, 3, 4, 5]
# Print each value in my_list. Note you can use the "in" keyword to iterate over a list.
for item in my_list:
print('The value of item is: ' + str(item))
# Print each index and value pair.
for i, value in enumerate(my_list):
print('The index value is: ' + str(i) + '. The value at i is: ' + str(value))
# Print each number from 0 to 9 using a while loop.
i = 0
while(i < 10):
print(i)
i += 1
# Print each key and dictionary value. Note that you can use the "in" keyword
# to iterate over dictionary keys.
my_dict = {'a': 'jill', 'b': 'tom', 'c': 'tim'}
for key in my_dict:
print(key + ', ' + my_dict[key])
Remember that Python requires correct indentation for code blocks to be interpreted correctly. Indentation for a block is usually four spaces, or one tab length.
SOLUTION:
[0, 1, 2, 3]Conditional Statements
Conditional statements use boolean logic to help guide our decision process: the statement is true or false. These statements are structured using comparison operators: greater than (>
), less than (<
), and equal to (==
).
Using conditional statements for control flow is accomplished in Python with the keywords: if
, else
, and elif
. When doing multiple comparisons in Python, one after the other, the first comparison always usesif
and the last comparison generally uses else
. If additional control flow is needed, elif
statements can be used; elif
stands for "else if".
num = 5
if num < 5:
print('The number is smaller than 5.')
elif num == 5:
print('The number equals 5.')
else:
print('The number is greater than 5.')
The code above would print: The number equals 5.
Control Structure Practice
In the following exercise you will finish writing smallest_positive
which is a function that finds the smallest positive number in a list.
Exercise 1
Start Quiz:
def smallest_positive(in_list):
# TODO: Define a control structure that finds the smallest positive
# number in in_list and returns the correct smallest number.
return 0
# Test cases
print(smallest_positive([4, -6, 7, 2, -4, 10]))
# Correct output: 2
print(smallest_positive([.2, 5, 3, -.1, 7, 7, 6]))
# Correct output: 0.2
def smallest_positive(in_list):
# TODO: Define a control structure that finds the smallest positive
# number in in_list and returns the correct smallest number.
smallest_pos = None
for num in in_list:
if num > 0:
# Note: we use a logical "or" in this solution to form
# the conditional statement, although this was
# not introduced above.
if smallest_pos == None or num < smallest_pos:
smallest_pos = num
return smallest_pos
# Test cases
print(smallest_positive([4, -6, 7, 2, -4, 10]))
# Correct output: 2
print(smallest_positive([.2, 5, 3, -.1, 7, 7, 6]))
# Correct output: 0.2
User's Answer:
(Note: The answer done by the user is not guaranteed to be correct)
def smallest_positive(in_list):
# TODO: Define a control structure that finds the smallest positive
# number in in_list and returns the correct smallest number.
min = 999999999999999999999999999
for num in in_list:
if num < min and num > 0.0:
min = num
if len(in_list) > 1:
return min
else:
return None
# Test cases
print(smallest_positive([4, -6, 7, 2, -4, 10]))
# Correct output: 2
print(smallest_positive([.2, 5, 3, -.1, 7, 7, 6]))
# Correct output: 0.2
def smallest_positive(in_list):
# TODO: Define a control structure that finds the smallest positive
# number in in_list and returns the correct smallest number.
smallest_pos = None
for num in in_list:
if num > 0:
# Note: we use a logical "or" in this solution to form
# the conditional statement, although this was
# not introduced above.
if smallest_pos == None or num < smallest_pos:
smallest_pos = num
return smallest_pos
# Test cases
print(smallest_positive([4, -6, 7, 2, -4, 10]))
# Correct output: 2
print(smallest_positive([.2, 5, 3, -.1, 7, 7, 6]))
# Correct output: 0.2
Exercise 2
Now let's assume you are planning on taking some additional courses at your local educational institution, and you have acquired some data about the available courses and when they will be offered. In the following exercise, you will write control structures to process the data and return the semesters when a given course is offered.
You will need to complete the function when_offered(courses, course)
. This function accepts a "courses" data structure and a "course" string. The function should return a list of strings representing the semesters when the input course is offered. See the two test cases below for examples of correct results.
Since the when_offered
function accepts a dictionary data structure, you will find the
for <key> in <dictionary>:
<block>
construct useful, as this loops through the key values in a dictionary.
Start Quiz:
# This exercise uses a data structure that stores Udacity course information.
# The data structure format is:
# { <semester>: { <class>: { <property>: <value>, ... },
# ... },
# ... }
courses = {
'spring2020': { 'cs101': {'name': 'Building a Search Engine',
'teacher': 'Dave',
'assistant': 'Peter C.'},
'cs373': {'name': 'Programming a Robotic Car',
'teacher': 'Sebastian',
'assistant': 'Andy'}},
'fall2020': { 'cs101': {'name': 'Building a Search Engine',
'teacher': 'Dave',
'assistant': 'Sarah'},
'cs212': {'name': 'The Design of Computer Programs',
'teacher': 'Peter N.',
'assistant': 'Andy',
'prereq': 'cs101'},
'cs253': {'name': 'Web Application Engineering - Building a Blog',
'teacher': 'Steve',
'prereq': 'cs101'},
'cs262': {'name': 'Programming Languages - Building a Web Browser',
'teacher': 'Wes',
'assistant': 'Peter C.',
'prereq': 'cs101'},
'cs373': {'name': 'Programming a Robotic Car',
'teacher': 'Sebastian'},
'cs387': {'name': 'Applied Cryptography',
'teacher': 'Dave'}},
'spring2044': { 'cs001': {'name': 'Building a Quantum Holodeck',
'teacher': 'Dorina'},
'cs003': {'name': 'Programming a Robotic Robotics Teacher',
'teacher': 'Jasper'},
}
}
def when_offered(courses, course):
# TODO: Fill out the function here.
# TODO: Return list of semesters here.
return None
print(when_offered(courses, 'cs101'))
# Correct result:
# ['fall2020', 'spring2020']
print(when_offered(courses, 'bio893'))
# Correct result:
# []
# This exercise uses a data structure that stores Udacity course information.
# The data structure format is:
# { <semester>: { <class>: { <property>: <value>, ... },
# ... },
# ... }
courses = {
'spring2020': { 'cs101': {'name': 'Building a Search Engine',
'teacher': 'Dave',
'assistant': 'Peter C.'},
'cs373': {'name': 'Programming a Robotic Car',
'teacher': 'Sebastian',
'assistant': 'Andy'}},
'fall2020': { 'cs101': {'name': 'Building a Search Engine',
'teacher': 'Dave',
'assistant': 'Sarah'},
'cs212': {'name': 'The Design of Computer Programs',
'teacher': 'Peter N.',
'assistant': 'Andy',
'prereq': 'cs101'},
'cs253': {'name': 'Web Application Engineering - Building a Blog',
'teacher': 'Steve',
'prereq': 'cs101'},
'cs262': {'name': 'Programming Languages - Building a Web Browser',
'teacher': 'Wes',
'assistant': 'Peter C.',
'prereq': 'cs101'},
'cs373': {'name': 'Programming a Robotic Car',
'teacher': 'Sebastian'},
'cs387': {'name': 'Applied Cryptography',
'teacher': 'Dave'}},
'spring2044': { 'cs001': {'name': 'Building a Quantum Holodeck',
'teacher': 'Dorina'},
'cs003': {'name': 'Programming a Robotic Robotics Teacher',
'teacher': 'Jasper'},
}
}
# In this exercise, you will need to complete the function
# when_offered(courses, course). This function accepts a "courses"
# data structure and a "course" string.
# The function should return a list of strings representing the semesters
# when the input course is offered. See the two test cases below for examples
# of correct results.
def when_offered(courses, course):
# TODO: Fill out the function here.
semesters = []
for semester in courses:
if course in courses[semester]:
semesters.append(semester)
# TODO: Return list of semesters here.
return semesters
print(when_offered(courses, 'cs101'))
# Correct result:
# ['fall2020', 'spring2020']
print(when_offered(courses, 'bio893'))
# Correct result:
# []
User's Answer:
(Note: The answer done by the user is not guaranteed to be correct)
# This exercise uses a data structure that stores Udacity course information.
# The data structure format is:
# { <semester>: { <class>: { <property>: <value>, ... },
# ... },
# ... }
courses = {
'spring2020': { 'cs101': {'name': 'Building a Search Engine',
'teacher': 'Dave',
'assistant': 'Peter C.'},
'cs373': {'name': 'Programming a Robotic Car',
'teacher': 'Sebastian',
'assistant': 'Andy'}},
'fall2020': { 'cs101': {'name': 'Building a Search Engine',
'teacher': 'Dave',
'assistant': 'Sarah'},
'cs212': {'name': 'The Design of Computer Programs',
'teacher': 'Peter N.',
'assistant': 'Andy',
'prereq': 'cs101'},
'cs253': {'name': 'Web Application Engineering - Building a Blog',
'teacher': 'Steve',
'prereq': 'cs101'},
'cs262': {'name': 'Programming Languages - Building a Web Browser',
'teacher': 'Wes',
'assistant': 'Peter C.',
'prereq': 'cs101'},
'cs373': {'name': 'Programming a Robotic Car',
'teacher': 'Sebastian'},
'cs387': {'name': 'Applied Cryptography',
'teacher': 'Dave'}},
'spring2044': { 'cs001': {'name': 'Building a Quantum Holodeck',
'teacher': 'Dorina'},
'cs003': {'name': 'Programming a Robotic Robotics Teacher',
'teacher': 'Jasper'},
}
}
def when_offered(courses, course):
# TODO: Fill out the function here.
offered_list = []
for offered in courses:
course_info = courses[offered]
if course in course_info:
offered_list.append(offered)
# TODO: Return list of semesters here.
return offered_list
print(when_offered(courses, 'cs101'))
# Correct result:
# ['fall2020', 'spring2020']
print(when_offered(courses, 'bio893'))
# Correct result:
# []
# This exercise uses a data structure that stores Udacity course information.
# The data structure format is:
# { <semester>: { <class>: { <property>: <value>, ... },
# ... },
# ... }
courses = {
'spring2020': { 'cs101': {'name': 'Building a Search Engine',
'teacher': 'Dave',
'assistant': 'Peter C.'},
'cs373': {'name': 'Programming a Robotic Car',
'teacher': 'Sebastian',
'assistant': 'Andy'}},
'fall2020': { 'cs101': {'name': 'Building a Search Engine',
'teacher': 'Dave',
'assistant': 'Sarah'},
'cs212': {'name': 'The Design of Computer Programs',
'teacher': 'Peter N.',
'assistant': 'Andy',
'prereq': 'cs101'},
'cs253': {'name': 'Web Application Engineering - Building a Blog',
'teacher': 'Steve',
'prereq': 'cs101'},
'cs262': {'name': 'Programming Languages - Building a Web Browser',
'teacher': 'Wes',
'assistant': 'Peter C.',
'prereq': 'cs101'},
'cs373': {'name': 'Programming a Robotic Car',
'teacher': 'Sebastian'},
'cs387': {'name': 'Applied Cryptography',
'teacher': 'Dave'}},
'spring2044': { 'cs001': {'name': 'Building a Quantum Holodeck',
'teacher': 'Dorina'},
'cs003': {'name': 'Programming a Robotic Robotics Teacher',
'teacher': 'Jasper'},
}
}
# In this exercise, you will need to complete the function
# when_offered(courses, course). This function accepts a "courses"
# data structure and a "course" string.
# The function should return a list of strings representing the semesters
# when the input course is offered. See the two test cases below for examples
# of correct results.
def when_offered(courses, course):
# TODO: Fill out the function here.
semesters = []
for semester in courses:
if course in courses[semester]:
semesters.append(semester)
# TODO: Return list of semesters here.
return semesters
print(when_offered(courses, 'cs101'))
# Correct result:
# ['fall2020', 'spring2020']
print(when_offered(courses, 'bio893'))
# Correct result:
# []